<template>
  <el-drawer 
    v-model="visible" 
    :title="isEdit ? '编辑学生' : '添加学生'" 
    direction="rtl" 
    size="520px"
    :before-close="handleClose"
    class="premium-drawer"
  >
    <!-- 自定义头部 -->
    <template #header="{ titleId, titleClass }">
      <div class="drawer-header">
        <div class="header-icon">
          <el-icon size="24">
            <Avatar v-if="isEdit" />
            <UserFilled v-else />
          </el-icon>
        </div>
        <div class="header-content">
          <h3 :id="titleId" :class="titleClass">
            {{ isEdit ? '编辑学生' : '添加学生' }}
          </h3>
          <p class="header-subtitle">
            {{ isEdit ? '修改学生信息' : '创建新的学生账户' }}
          </p>
        </div>
      </div>
    </template>

    <div class="drawer-content">
      <el-form 
        ref="formRef" 
        :model="formData" 
        :rules="formRules" 
        label-width="100px" 
        label-position="top"
        class="premium-form"
      >
        <!-- 基本信息字段 -->
        <div class="form-grid">
          <el-form-item label="用户名" prop="username" class="form-item">
            <el-input 
              v-model="formData.username" 
              placeholder="请输入用户名"
              class="premium-input"
              clearable
            >
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="姓名" prop="realName" class="form-item">
            <el-input 
              v-model="formData.realName" 
              placeholder="请输入学生姓名"
              class="premium-input"
              clearable
            >
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="性别" prop="gender" class="form-item">
            <el-select 
              v-model="formData.gender" 
              placeholder="请选择性别" 
              style="width: 100%"
              class="premium-select"
              clearable
            >
              <el-option label="男" value="male" />
              <el-option label="女" value="female" />
            </el-select>
          </el-form-item>
        </div>

        <div class="form-grid">
          <el-form-item label="学号" prop="studentCode" class="form-item">
            <el-input 
              v-model="formData.studentCode" 
              placeholder="请输入学号"
              class="premium-input"
              clearable
            >
              <template #prefix>
                <el-icon><CreditCard /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="学校" prop="school" class="form-item">
            <el-select 
              v-model="formData.school" 
              placeholder="请选择学校" 
              style="width: 100%"
              class="premium-select"
              clearable
            >
              <el-option label="清华大学" value="清华大学" />
              <el-option label="重庆大学" value="重庆大学" />
              <el-option label="燕山大学" value="燕山大学" />
              <el-option label="北京邮电大学" value="北京邮电大学" />
            </el-select>
          </el-form-item>
        </div>

        <el-form-item label="专业" prop="major" class="form-item full-width">
          <el-select 
            v-model="formData.major" 
            placeholder="请选择专业" 
            style="width: 100%"
            class="premium-select"
            clearable
          >
            <el-option label="计算机科学与技术" value="计算机科学与技术" />
            <el-option label="软件工程" value="软件工程" />
            <el-option label="网络工程" value="网络工程" />
            <el-option label="信息安全" value="信息安全" />
          </el-select>
        </el-form-item>

        <div class="form-grid">
          <el-form-item label="手机号" prop="phone" class="form-item">
            <el-input 
              v-model="formData.phone" 
              placeholder="请输入手机号"
              class="premium-input"
              clearable
            >
              <template #prefix>
                <el-icon><Phone /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email" class="form-item">
            <el-input 
              v-model="formData.email" 
              placeholder="请输入邮箱地址"
              class="premium-input"
              clearable
            >
              <template #prefix>
                <el-icon><Message /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </div>
        <el-form-item label="生日" prop="birthday" class="form-item-enhanced">
              <el-date-picker v-model="formData.birthday" type="date" placeholder="选择出生日期" class="enhanced-date-picker" />
          </el-form-item>
        <el-form-item label="账户状态" prop="status" class="form-item-enhanced">
            <el-radio-group v-model="formData.status" class="enhanced-radio-group">
              <el-radio label="在校" class="enhanced-radio status-active">在校</el-radio>
              <el-radio label="休学" class="enhanced-radio status-inactive">休学</el-radio>
            </el-radio-group>
          </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button 
          @click="handleClose"
          class="cancel-btn"
          size="large"
        >
          取消
        </el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit" 
          :loading="submitting"
          class="submit-btn"
          size="large"
        >
          <el-icon v-if="!submitting">
            <Check v-if="isEdit" />
            <Plus v-else />
          </el-icon>
          {{ isEdit ? '更新' : '添加' }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  User, Message, Phone, CreditCard, 
  Lock, Select, Check, Plus, Avatar, UserFilled,
  Warning, InfoFilled
} from '@element-plus/icons-vue'
import { postJson,get } from '@/axios'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  studentData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:visible', 'submit'])

// 响应式数据
const formRef = ref()
const submitting = ref(false)

// 表单数据
const defaultFormData = {
  id: null,
  username:'',
  realName: '',
  gender: '',
  studentCode: '',
  birthday:'',
  class: '',
  major: '',
  phone: '',
  email: '',
  enrollmentDate: '',
  status: '在校',
  password: '123456'
}

const formData = reactive({ ...defaultFormData })

// 计算属性
const visible = computed({
  get() {
    return props.visible
  },
  set(value) {
    emit('update:visible', value)
  }
})

// 监听器
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 重置表单数据
    if (props.isEdit && props.studentData) {
      // 编辑模式，填充数据
      Object.assign(formData, {
        ...defaultFormData,
        ...props.studentData,
        status: formData.status === '在职' ? true : false
      })
    } else {
      // 新增模式，重置表单
      Object.assign(formData, defaultFormData)
    }

    // 重置表单验证
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }
});

// 表单验证规则
const formRules = reactive({
  realName: [
    { required: true, message: '请输入学生姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在2-20个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  studentCode: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    {
        validator: (rule, value, callback) => {
          if (!value) {
            callback()
            return
          }
          // 编辑模式下，如果工号没变化，不需要检查
          if (props.isEdit && value === props.studentData?.studentCode) {
            callback()
            return
          }
          
          checkFieldUnique('studentCode', value, props.isEdit ? formData.id : null)
            .then(isUnique => {
              if (isUnique) {
                callback()
              } else {
                callback(new Error('学号已被其他学生使用'))
              }
            })
            .catch(() => {
              callback(new Error('检查学号唯一性失败'))
            })
        },
        trigger: 'blur'
      }
  ],
  class: [
    { required: true, message: '请选择班级', trigger: 'change' }
  ],
  major: [
    { required: true, message: '请选择专业', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
    {
        validator: (rule, value, callback) => {
          if (!value) {
            callback()
            return
          }
          // 编辑模式下，如果手机号没变化，不需要检查
          if (props.isEdit && value === props.studentData?.phone) {
            callback()
            return
          }
          
          checkFieldUnique('phone', value, props.isEdit ? formData.id : null)
            .then(isUnique => {
              if (isUnique) {
                callback()
              } else {
                callback(new Error('手机号已被其他学生使用'))
              }
            })
            .catch(() => {
              callback(new Error('检查手机号唯一性失败'))
            })
        },
        trigger: 'blur'
      }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' },
    {
        validator: (rule, value, callback) => {
          if (!value) {
            callback()
            return
          }
          // 编辑模式下，如果邮箱没变化，不需要检查
          if (props.isEdit && value === props.studentData?.email) {
            callback()
            return
          }
          
          checkFieldUnique('email', value, props.isEdit ? formData.id : null)
            .then(isUnique => {
              if (isUnique) {
                callback()
              } else {
                callback(new Error('邮箱已被其他学生使用'))
              }
            })
            .catch(() => {
              callback(new Error('检查邮箱唯一性失败'))
            })
        },
        trigger: 'blur'
      }
  ],
  enrollmentDate: [
    { required: true, message: '请选择入学时间', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择账户状态', trigger: 'change' }
  ],
  password: [
    {
      required: !props.isEdit,
      message: '请输入登录密码',
      trigger: 'blur'
    },
    { min: 6, max: 20, message: '密码长度在6-20个字符', trigger: 'blur' }
  ],
  birthday: [
      { required: true, message: '请选择出生时间', trigger: 'change' }
  ]
})

//添加检查唯一性的方法
const checkFieldUnique = async (field, value, excludeId) => {
  try {
    const response = await get('/umsStudent/checkUnique', {
      field,
      value,
      excludeId
    })
    return !response // 如果返回true表示被占用，false表示可用
  } catch (error) {
    console.error('检查唯一性失败:', error)
    return false
  }
}

// 提交处理
const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    submitting.value = true;

    // 准备提交数据
    const submitData = {
      ...formData,
      birthday: formData.birthday ? formatDate(formData.birthday) : formatDate(new Date()),
      status: formData.status === '在校' // 转换为后端需要的布尔值
    };

    // 调用不同的API
    const apiUrl = props.isEdit 
      ? `/umsStudent/updateById/${formData.id}` 
      : '/umsStudent/save';
    
    const response = await postJson(apiUrl, submitData);

    emit('submit');
    ElMessage.success(props.isEdit ? '学生信息更新成功' : '学生添加成功');
    handleClose();
  } catch (error) {
    console.error('表单提交失败:', error);
    ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message));
  } finally {
    submitting.value = false;
  }
}

const handleClose = () => {
  emit('update:visible', false)
}

// 日期格式化辅助函数
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}
</script>

<style scoped lang="scss">
.premium-drawer {
  :deep(.el-drawer) {
    background: white;
    box-shadow: -10px 0 30px rgba(0, 0, 0, 0.1);
  }

  :deep(.el-drawer__header) {
    margin-bottom: 0;
    padding: 0;
    border-bottom: none;
  }

  :deep(.el-drawer__title) {
    display: none;
  }

  :deep(.el-drawer__body) {
    padding: 0;
    display: flex;
    flex-direction: column;
  }
}

.drawer-header {
  display: flex;
  align-items: center;
  padding: 24px 24px 20px;
  background: linear-gradient(135deg, #8BE1F1 0%, #5CB6ED 100%);
  color: white;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    width: 100px;
    height: 100px;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 50%;
    transform: translate(30px, -30px);
  }

  .header-icon {
    width: 56px;
    height: 56px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.3);
  }

  .header-content {
    h3 {
      margin: 0 0 4px 0;
      font-size: 20px;
      font-weight: 600;
      color: white;
    }

    .header-subtitle {
      margin: 0;
      font-size: 14px;
      color: rgba(255, 255, 255, 0.8);
    }
  }
}

.drawer-content {
  flex: 1;
  padding: 32px 24px 24px;
  overflow-y: auto;
  background: white;

  // 自定义滚动条
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f3f4;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: linear-gradient(135deg, #8BE1F1, #5CB6ED);
    border-radius: 3px;

    &:hover {
      background: linear-gradient(135deg, #7AD1E1, #4CA6DD);
    }
  }
}

.premium-form {
  .form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .form-item {
    &.full-width {
      grid-column: 1 / -1;
    }

    :deep(.el-form-item__label) {
      font-weight: 600;
      color: #374151;
      font-size: 14px;
      margin-bottom: 8px;
    }

    :deep(.el-form-item__content) {
      line-height: 1;
    }
  }

  .premium-input {
    :deep(.el-input__wrapper) {
      background: #f8fafc;
      border: 2px solid #e2e8f0;
      border-radius: 12px;
      padding: 12px 16px;
      transition: all 0.3s ease;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);

      &:hover {
        border-color: #cbd5e1;
        background: white;
      }

      &.is-focus {
        border-color: #8BE1F1;
        background: white;
        box-shadow: 0 0 0 4px rgba(139, 225, 241, 0.1);
      }
    }

    :deep(.el-input__inner) {
      font-size: 14px;
      color: #1f2937;

      &::placeholder {
        color: #9ca3af;
      }
    }

    :deep(.el-input__prefix) {
      color: #6b7280;
    }
  }

  .premium-select {
    :deep(.el-select__wrapper) {
      background: #f8fafc;
      border: 2px solid #e2e8f0;
      border-radius: 12px;
      padding: 12px 16px;
      transition: all 0.3s ease;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);

      &:hover {
        border-color: #cbd5e1;
        background: white;
      }

      &.is-focus {
        border-color: #8BE1F1;
        background: white;
        box-shadow: 0 0 0 4px rgba(139, 225, 241, 0.1);
      }
    }

    :deep(.el-select__placeholder) {
      color: #9ca3af;
    }

    :deep(.el-select__prefix) {
      color: #6b7280;
    }
  }

  .premium-radio-group {
    display: flex;
    gap: 24px;

    .premium-radio {
      :deep(.el-radio__input) {
        .el-radio__inner {
          width: 18px;
          height: 18px;
          border: 2px solid #d1d5db;
          border-radius: 50%;

          &:hover {
            border-color: #8BE1F1;
          }
        }

        &.is-checked .el-radio__inner {
          background: linear-gradient(135deg, #8BE1F1 0%, #5CB6ED 100%);
          border-color: #8BE1F1;

          &::after {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: white;
          }
        }
      }

      :deep(.el-radio__label) {
        font-size: 0;
      }

      .radio-content {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 14px;
        font-weight: 500;
        color: #374151;

        .radio-icon {
          &.success {
            color: #10b981;
          }

          &.warning {
            color: #f59e0b;
          }

          &.info {
            color: #8BE1F1;
          }
        }
      }
    }
  }

  .form-divider {
    display: flex;
    align-items: center;
    margin: 24px 0;
    color: #6b7280;

    .divider-line {
      flex: 1;
      height: 1px;
      background: #e5e7eb;
    }

    .divider-text {
      padding: 0 16px;
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 14px;
      font-weight: 500;
      white-space: nowrap;
    }
  }
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding: 24px;
  background: white;
  border-top: 1px solid #e5e7eb;
  box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.05);

  .cancel-btn {
    :deep(.el-button) {
      background: #f3f4f6;
      border: 2px solid #e5e7eb;
      color: #6b7280;
      border-radius: 12px;
      padding: 12px 24px;
      font-weight: 500;
      transition: all 0.3s ease;

      &:hover {
        background: #e5e7eb;
        border-color: #d1d5db;
        color: #374151;
        transform: translateY(-1px);
      }
    }
  }

  .submit-btn {
    :deep(.el-button) {
      background: linear-gradient(135deg, #8BE1F1 0%, #5CB6ED 100%);
      border: none;
      border-radius: 12px;
      padding: 12px 24px;
      font-weight: 500;
      box-shadow: 0 4px 12px rgba(139, 225, 241, 0.3);
      transition: all 0.3s ease;

      &:hover {
        background: linear-gradient(135deg, #7AD1E1 0%, #4CA6DD 100%);
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(139, 225, 241, 0.4);
      }

      &:active {
        transform: translateY(0);
      }

      .el-icon {
        margin-right: 8px;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .drawer-content {
    padding: 24px 16px 16px;
  }

  .premium-form {
    .form-grid {
      grid-template-columns: 1fr;
      gap: 16px;
    }

    .form-divider {
      margin: 24px 0 20px 0;

      .divider-text {
        padding: 0 12px;
        font-size: 13px;
        height: 32px;
        min-width: 100px;
      }
    }
  }

  .drawer-footer {
    padding: 20px 16px;
    
    .cancel-btn,
    .submit-btn {
      :deep(.el-button) {
        padding: 10px 20px;
      }
    }
  }
}

// 动画效果
@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.premium-form {
  animation: slideInRight 0.4s ease;
}
</style>